import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_frame/common/app_config.dart';
import 'package:flutter_frame/common/user_manager.dart';
import 'package:flutter_frame/utils/log_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'common/common_config.dart';
import 'common/router.dart';
import 'assets/color_config.dart';
import 'assets/language/translation.dart';
import 'utils/theme_util.dart';
import 'weiget/default_404.dart';
import 'weiget/loading_widget.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  logger(kReleaseMode);
  await AppConfig().initData();
  runApp(MyApp(routerName: UserManager().isLogin() ? Routers.tabBar : Routers.login));
}

class MyApp extends StatefulWidget {
  String? routerName;

  MyApp({Key? key, this.routerName}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _MyApp();
}

class _MyApp extends State<MyApp> {
  bool initialCallback = false;

  @override
  void initState() {
    super.initState();
    EasyLoading.instance
      ..indicatorType = EasyLoadingIndicatorType.fadingCircle
      ..loadingStyle = EasyLoadingStyle.custom
      ..backgroundColor = const Color(0x99000000)
      ..indicatorColor = const Color(0xffFFFFFF)
      ..textColor = const Color(0xffFFFFFF)
      ..indicatorSize = 45.0
      ..boxShadow = []
      ..contentPadding = const EdgeInsets.all(10)
      ..progressColor = Colors.white
      ..userInteractions = true;
    // if (CommonConfig.configSystemCheckUpdate) {
    //   scheduleMicrotask(() {
    //     Future.delayed(const Duration(milliseconds: 2000), () {
    //       //检查版本更新
    //       VersionCheck.checkVersionUpdate(
    //           context: Get.overlayContext ?? context);
    //     });
    //   });
    // }
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      useInheritedMediaQuery: true,
      minTextAdapt: true,
      splitScreenMode: true,
      designSize: const Size(designWidth, designHeight),
      builder: (BuildContext context, Widget? child) {
        EasyLoading.instance.indicatorSize = 40.w;
        var translation = Translation();

        return RefreshConfiguration(
          headerBuilder: () => GetPlatform.isAndroid
              ? MaterialClassicHeader(color: ColorConfig.colorPrimary)
              : const ClassicHeader(),
          footerBuilder: () => GetPlatform.isAndroid
              ? CustomFooter(
                  loadStyle: LoadStyle.ShowWhenLoading,
                  builder: (BuildContext context, LoadStatus? mode) {
                    if (mode == LoadStatus.canLoading ||
                        mode == LoadStatus.loading) {
                      return const LoadingWidget();
                    }
                    return Container();
                  },
                )
              : const ClassicFooter(
                  loadStyle: LoadStyle.ShowWhenLoading,
                ),
          child: GetMaterialApp(
            theme: ThemeUtil.obtainThemeData(true),
            darkTheme: ThemeUtil.obtainThemeData(false),
            themeMode: ThemeUtil.getDeviceThemeMode(),
            localizationsDelegates: const [
              RefreshLocalizations.delegate,
              //GlobalWidgetsLocalization.delegate,
              //GlobalMaterialLocalizations.delegate
            ],
            supportedLocales:
                translation.keys.keys.map((e) => Locale(e)).toList(),
            translations: translation,
            locale: Locale('en', 'US'),
            initialRoute: widget.routerName ?? Routers.login,
            routes: Routers.routerMap,
            fallbackLocale: Locale(translation.keys.keys.first),
            unknownRoute:
                GetPage(name: '/notFound', page: () => const Default404()),
            navigatorKey: Get.key,
            navigatorObservers: [GetObserver()],
            builder: EasyLoading.init(),
          ),
        );
      },
    );
  }
}
